<template>
	<view class="bg-white">
		<view class="u-p-28">

			<u-alert-tips show-icon type="warning" title="温馨提示" description="领养从真实开始，以下信息有助于送养人了解您的真实情况，请尽量详细填写。">
			</u-alert-tips>

			<u-form :model="form" :label-style="labelStyle" :border-bottom="false" label-position="top" ref="uForm">
				<u-form-item :border-bottom="false" label="昵称">
					<u-input :clearable="false" :custom-style="inputStyle" v-model="form.nickname" placeholder="请输入" />
				</u-form-item>

				<u-form-item :border-bottom="false" label="性别">
					<radio-button height="36px" v-model="form.sex" :list="sexList" width="60%"></radio-button>

				</u-form-item>

				<u-form-item :border-bottom="false" label="婚姻状况">
					<radio-button height="36px" v-model="form.marital_status" :list="maritalStatusList"></radio-button>
				</u-form-item>

				<u-form-item :border-bottom="false" label="住房状况">
					<radio-button height="36px" v-model="form.house_status" :list="houseStatusList"></radio-button>
				</u-form-item>


				<view class="u-m-t-28 bg-white border-r-6">
					<u-form-item label-width="150" :border-bottom="false" label="出生日期">
						<view class="u-rela">
							<u-icon size="40" color="#808080" class="u-abso arrow" name="arrow-right"></u-icon>
							<u-input disabled @click="showTimeSelect = true" :custom-style="inputStyle"
								v-model="form.birthday" placeholder="请选择日期" />
						</view>

						<u-picker v-model="showTimeSelect" mode="time" @confirm="handleSelectTime">
						</u-picker>

					</u-form-item>
				</view>

				<u-form-item :border-bottom="false" label="职业">
					<u-input :clearable="false" :custom-style="inputStyle" v-model="form.job" placeholder="请输入" />
				</u-form-item>

				<u-form-item :border-bottom="false" label="地址">
					<view class="u-rela">
						<u-icon size="40" color="#808080" class="u-abso arrow" name="map"></u-icon>
						<u-input disabled @click="chooseLocation" :clearable="false" :custom-style="inputStyle"
							v-model="form.location" placeholder="请选择" />
					</view>
				</u-form-item>

				<u-form-item :border-bottom="false" label="养宠经验">
					<u-input height="220" :clearable="false" :custom-style="textareaStyle" type="textarea"
						v-model="form.experience" placeholder="如没有请注明“无养宠经验”" />
				</u-form-item>

				<u-form-item :border-bottom="false" label="申请语">
					<u-input height="220" :clearable="false" :custom-style="textareaStyle" type="textarea"
						v-model="form.apply_term" placeholder="想对送养人说的话，都写在这里吧~" />
				</u-form-item>

				<u-form-item :border-bottom="false" label="手机">
					<view class="u-rela">
						<button :disabled="form.mobile" class="mobile-btn" open-type="getPhoneNumber"
							@getphonenumber="getMobile">一键获取</button>
						<u-input :custom-style="inputStyle" v-model="form.mobile" placeholder="请点击获取" :clearable="false"
							disabled />
					</view>
				</u-form-item>

				<u-form-item :border-bottom="false" label="微信">
					<u-input :clearable="false" :custom-style="inputStyle" v-model="form.wechat" placeholder="请输入" />
				</u-form-item>

				<u-form-item :border-bottom="false" label="QQ号">
					<u-input :clearable="false" :custom-style="inputStyle" v-model="form.qq" placeholder="请输入" />
				</u-form-item>

				<u-form-item :border-bottom="false" label="微信二维码">
					<upload dir="adopt_apply" v-model="form.wechat_qrcode"></upload>
				</u-form-item>

				<view class="submit">
					<view class="btn" @click="submit">提交申请</view>
				</view>


			</u-form>
		</view>

		<!-- 返回顶部 -->
		<u-back-top :duration="1000" :scroll-top="scrollTop"></u-back-top>
	</view>
</template>

<script>
	import indexCard from '@/components/indexCard/indexCard.vue';
	import radioButton from '@/components/radioButton/radioButton.vue';
	import upload from '@/pagesIndex/components/upload/upload.vue';
	import {
		adoptsApply,
	} from '@/api/index';
	import {
		getMobile,
		getUserInfo
	} from '@/api/user';
	import {
		getTemplateIds
	} from '@/api/common';

	import {
		sexList,
		maritalStatusList,
		houseStatusList
	} from '@/const';
	export default {
		components: {
			indexCard,
			radioButton,
			upload
		},
		data() {
			return {
				form: {
					"location": "",
					"mobile": "",
					"nickname": "",
					"birthday": "",
					marital_status: 1,
					house_status: 1,
				},
				// form: {
				// 	"location": "四川省成都市双流区丛桂街1号",
				// 	"mobile": "13245678654",
				// 	"nickname": "劫",
				// 	"birthday": "2001-06-26",
				// 	"sex": 1,
				// 	"marital_status": 2,
				// 	"house_status": 2,
				// 	"job": "刺客",
				// 	"lat": 30.57447,
				// 	"lng": 103.92377,
				// 	"experience": "6年",
				// 	"apply_term": "哈沙克",
				// 	"wechat": "345",
				// 	"qq": "3456",
				// 	"wechat_qrcode": "adopt_apply/09fd5eacede9167f924da089c57e33af.jpeg"
				// },
				sexList: [sexList[0], sexList[1]],
				maritalStatusList,
				houseStatusList,
				scrollTop: 0,
				showTimeSelect: false,
				labelStyle: {
					borderLeft: '3px solid  #FFCF0B',
					paddingLeft: '5px',
					color: '#333',
					fontSize: '16px',
					height: '16px',
					marginBottom: '10rpx'
				},
				inputStyle: {
					height: '40px',
					background: '#F6F7FB',
					borderRadius: '4px',
					padding: '0 10px',
				},
				textareaStyle: {
					height: '40px',
					background: '#F6F7FB',
					borderRadius: '4px',
					padding: '10px',
				},
				code: '',
			};
		},
		onLoad(options) {
			this.form.adopt_id = options.id;
			uni.login({
				provider: 'weixin',
				success: (res) => {
					this.code = res.code;
				}
			})
		},
		mounted() {
			this.getUserInfo();
		},
		methods: {
			async getUserInfo() {
				const res = await getUserInfo();
				this.form.nickname = res.data.nickname;
				this.form.qq = res.data.qq;
				this.form.sex = res.data.sex;
				this.form.wechat = res.data.wechat;

				console.log(res);
			},
			onPageScroll(e) {
				this.scrollTop = e.scrollTop;
			},
			handleSelectTime(val) {
				let {
					year,
					month,
					day
				} = val;
				const current = parseInt(+new Date() / 1000);
				if (val.timestamp > current) {
					year = new Date().getFullYear();
					month = new Date().getMonth() + 1;
					day = new Date().getDate();
				}
				this.form.birthday = `${year}-${month}-${day}`;
			},
			chooseLocation() {
				uni.getLocation({
					success: (res) => {
						uni.chooseLocation({
							latitude: res.latitude,
							longitude: res.longitude,
							success: (sub) => {
								this.form.location = sub.address;
								this.form.lat = sub.latitude;
								this.form.lng = sub.longitude;
							}
						})
					}
				})
			},

			async getMobile(e) {
				const info = e.detail;
				if (e.detail.errMsg != "getPhoneNumber:fail user deny") {
					const sub = await getMobile({
						code: this.code,
						iv: info.iv,
						encryptedData: info.encryptedData
					});
					this.form.mobile = sub.data.mobile;
				}
			},
			goMessageGetInfo(id) {
				// 要求到申请领养详情页面点击返回直接返回到领养详情页面
				uni.redirectTo({
					url: `/pagesMy/messageGetInfo/messageGetInfo?source=3&id=${id}`
				})
			},
			async submit() {
				const postData = Object.assign({}, this.form);
				postData.wechat_qrcode = postData.wechat_qrcode && postData.wechat_qrcode[0].attachment || '';
				const res = await adoptsApply(postData);
				this.requestSubscribeMessage(res.data.apply_id);
			},
			async requestSubscribeMessage(apply_id) {
				const respone = await getTemplateIds();
				const tmplIds = respone.data.adopt_apply_template[0];
				const _this = this;
				wx.getSetting({
					withSubscriptions: true, //  这里设置为true,下面才会返回mainSwitch
					success: function(res) {
						console.log('res', res);
						// 调起授权界面弹窗
						if (res.subscriptionsSetting.mainSwitch) { // 用户打开了订阅消息总开关
							if (res.subscriptionsSetting.itemSettings !=
								null) { // 用户同意总是保持是否推送消息的选择, 这里表示以后不会再拉起推送消息的授权
								let moIdState = res.subscriptionsSetting.itemSettings[
									tmplIds]; // 用户同意的消息模板id
								if (moIdState === 'accept') {
									console.log('接受了消息推送');

								} else if (moIdState === 'reject') {
									console.log("拒绝消息推送");

								} else if (moIdState === 'ban') {
									console.log("已被后台封禁");

								}
							} else {
								// 当用户没有点击 ’总是保持以上选择，不再询问‘  按钮。那每次执到这都会拉起授权弹窗
								wx.showModal({
									title: '提示',
									content: '请授权开通服务通知',
									showCancel: true,
									success: function(ress) {
										if (ress.confirm) {
											wx.requestSubscribeMessage({ // 调起消息订阅界面
												tmplIds: [tmplIds],
												success(res) {
													console.log('订阅消息 成功 ');
													console.log(res);
													_this.goMessageGetInfo(apply_id);
												},
												fail(er) {
													console.log("订阅消息 失败 ");
													console.log(er);
													_this.goMessageGetInfo(apply_id);
												}
											})

										} else if (ress.cancel) {
											_this.goMessageGetInfo(apply_id);
										}
									}
								})
							}

						} else {
							console.log('订阅消息未开启')
						}
					},
					fail: function(error) {
						console.log(error);
					},
				})

			}
		}
	}
</script>

<style lang="scss" scoped>
	.arrow {
		right: 28rpx;
		z-index: 5;
		top: 50%;
		transform: translateY(-50%);
		color: #FFCF0B;
	}

	.submit {
		padding: 32rpx;

		.btn {
			height: 44px;
			line-height: 44px;
			color: #333333;
			font-size: 16px;
			background: #FFCF0B;
			border-radius: 22px;
			text-align: center;
		}
	}

	.mobile-btn {
		position: absolute;
		top: 0;
		right: 0;
		z-index: 5;
		background: transparent;
		color: #FFCF0B;
		font-size: 12px;
		line-height: 40px;

		&::after {
			border: none;
		}
	}
</style>
